package com.kingyun.gpsinspection.purificationservice.services.iam.innerservice.adm.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cqhilink.api.common.utils.UniqueUtil;
import com.kingyun.gpsinspection.purificationservice.common.activiti.ActivitiConstants;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.iam.adm.AutoApplyMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.iam.adm.CarTransferMapper;
import com.kingyun.gpsinspection.purificationservice.facade.model.iam.adm.AutoApply;
import com.kingyun.gpsinspection.purificationservice.facade.model.iam.adm.CarTransferVo;
import com.kingyun.gpsinspection.purificationservice.facade.model.jsm.EmployeeVo;
import com.kingyun.gpsinspection.purificationservice.facade.service.activiti.base.WorkFlowService;
import com.kingyun.gpsinspection.purificationservice.facade.service.iam.adm.CarTransferService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/**
 * Created by jiangjx on 2017/7/11.
 */
public class CarTransferServiceImpl implements CarTransferService {
    public static final String FLOWKEY = "carDispatch";
    @Autowired
    private CarTransferMapper carTransferMapper;
    @Autowired
    private WorkFlowService workFlowService;
    @Autowired
    private AutoApplyMapper autoApplyMapper;

    /**
     * 查询分页数据
     *
     * @param carTransferVo 查询条件
     */
    @Override
    public JSONObject queryListInfo(CarTransferVo carTransferVo) throws Exception {
        JSONObject object = new JSONObject();
        carTransferVo.setLimit(carTransferVo.getLimit() == null ? 10 : carTransferVo.getLimit());
        carTransferVo.setOffset(carTransferVo.getOffset() == null ? 0 : carTransferVo.getOffset());
        object.put("rows", JSON.toJSON(carTransferMapper.queryList(carTransferVo)));
        object.put("total", carTransferMapper.queryCount(carTransferVo));
        return object;
    }

    /**
     * 添加调度单信息
     *
     * @param carTransferVo 调派单信息
     * @param autoApplies   申请单列表
     * @param loginUser     当前登陆人
     */
    @Override
    public void saveInfo(CarTransferVo carTransferVo, List<AutoApply> autoApplies, EmployeeVo loginUser) throws Exception {
        Map<String, Object> variables = new HashMap<>();
        if (null != carTransferVo) {
            // 设置主键
            carTransferVo.setId(UniqueUtil.uuid());
            //创建时间
            carTransferVo.setCreateTime(new Date());
            //创建人
            carTransferVo.setCreateUser(loginUser.getEmployeeId());
            //修改时间
            carTransferVo.setModifyTime(new Date());
            //修改人
            carTransferVo.setModifyUser(loginUser.getEmployeeId());
            //状态：0审批中，1已完成，2驳回，3废弃
            carTransferVo.setState(0);

            formatData(carTransferVo, autoApplies, loginUser, 1);

            //保存数据
            int i = carTransferMapper.insertSelective(carTransferVo);
            if (i > 0) {
                //发起流程
                String[] str = {carTransferVo.getFirstApproval()};
                variables.put(ActivitiConstants.MANUAL_PERSON, new ArrayList<>(Arrays.asList(str)));
                workFlowService.startProcessInstanceByKey(FLOWKEY, carTransferVo.getId(), variables, loginUser.getEmployeeId());
            }
        }
    }

    /**
     * 加载待我审批的调派单
     *
     * @param carTransferVo 查询条件
     */
    @Override
    public JSONObject loadMyTodoListInfo(CarTransferVo carTransferVo) throws Exception {
        JSONObject object = new JSONObject();
        carTransferVo.setLimit(carTransferVo.getLimit() == null ? 10 : carTransferVo.getLimit());
        carTransferVo.setOffset(carTransferVo.getOffset() == null ? 0 : carTransferVo.getOffset());
        object.put("total", carTransferMapper.queryMyTodoCount(carTransferVo));
        object.put("rows", JSON.toJSON(carTransferMapper.queryMyTodoList(carTransferVo)));
        return object;
    }

    /**
     * 通过id查询调派单详细信息
     *
     * @param id 调派单主键id
     */
    @Override
    public CarTransferVo selectByPrimaryKey(String id) throws Exception {
        return carTransferMapper.selectByPrimaryKey(id);
    }

    /**
     * 审批流程
     *
     * @param carTransferVo
     * @param loginUser
     * @param autoApplies
     */
    @Override
    public void dispose(CarTransferVo carTransferVo, List<AutoApply> autoApplies, EmployeeVo loginUser) throws Exception {
        Map<String, Object> variables = new HashMap<>();
        variables.put("cond", carTransferVo.getState());
        if (carTransferVo.getState() == 1) {
            if (carTransferVo.getStepName().contains("node1")) {
                //设置第二审批人
                String[] str = {carTransferVo.getSecondApproval()};
                variables.put(ActivitiConstants.MANUAL_PERSON, new ArrayList<>(Arrays.asList(str)));
            } else if (carTransferVo.getStepName().contains("node2")) {
                //设置司机
                String[] str = {carTransferVo.getDriverId()};
                variables.put(ActivitiConstants.MANUAL_PERSON, new ArrayList<>(Arrays.asList(str)));
            } else if (carTransferVo.getStepName().contains("node3")) {
                //修改调派单状态
                carTransferMapper.updateByPrimaryKeySelective(carTransferVo);
                //修改申请单状态
                updateAutoApplies(carTransferVo.getAutoApplyId(), loginUser, 2);
            } else if (carTransferVo.getStepName().contains("node4")) {
                //从新提交
                carTransferVo.setState(0);
                //清空申请单信息
                carTransferVo.setAutoApplyId(null);
                carTransferVo.setContacts(null);
                carTransferVo.setNumberOfPassenger(null);
                carTransferVo.setUseDepartment(null);
                formatData(carTransferVo, autoApplies, loginUser, 1);
                carTransferMapper.updateByPrimaryKeySelective(carTransferVo);
                //设置审批人
                String[] str = {carTransferVo.getFirstApproval()};
                variables.put(ActivitiConstants.MANUAL_PERSON, new ArrayList<>(Arrays.asList(str)));
            }
        } else if (carTransferVo.getState() == 2) {
            if (!carTransferVo.getStepName().contains("node4")) {
                //驳回
                rejectTask(carTransferVo, variables, loginUser);
            } else {
                //废弃
                carTransferVo.setState(3);
                carTransferMapper.updateByPrimaryKeySelective(carTransferVo);
            }
        }
        workFlowService.completeTask(carTransferVo.getTaskId(), variables, carTransferVo.getComments(), loginUser.getEmployeeId());
    }

    /**
     * 废弃后修改申请单为可用状态
     */
    private void updateAutoApplies(String autoApplyIds, EmployeeVo loginUser, int flag) {
        String[] ids = autoApplyIds.contains("，") ? autoApplyIds.split("，") : new String[]{autoApplyIds};
        for (String id : ids) {
            AutoApply autoApply = new AutoApply();
            autoApply.setAutoApplyId(id);
            autoApply.setModifyTime(new Date());
            autoApply.setModifierId(loginUser.getEmployeeId());
            if (flag == 1) autoApply.setStatus(new Short("1"));
            else if (flag == 2) autoApply.setStatus(new Short("5"));
            autoApplyMapper.updateByPrimaryKeySelective(autoApply);
        }

    }

    /**
     * 封装申请单信息，修改申请单状态
     */
    private void formatData(CarTransferVo carTransferVo, List<AutoApply> autoApplies, EmployeeVo loginUser, int flag) {
        for (AutoApply autoApply : autoApplies) {
            //申请单id
            carTransferVo.setAutoApplyId(null == carTransferVo.getAutoApplyId() ? autoApply.getAutoApplyId() : carTransferVo.getAutoApplyId() + "，" + autoApply.getAutoApplyId());
            //联系人
            carTransferVo.setContacts(null == carTransferVo.getContacts() ? autoApply.getOperatorName() : carTransferVo.getContacts() + "，" + autoApply.getOperatorName());
            //人数
            carTransferVo.setNumberOfPassenger(null == carTransferVo.getNumberOfPassenger() ? autoApply.getPersonTotal() : carTransferVo.getNumberOfPassenger() + autoApply.getPersonTotal());
            //用车部门
            carTransferVo.setUseDepartment(null == carTransferVo.getUseDepartment() ? autoApply.getDepName() : carTransferVo.getUseDepartment() + "，" + autoApply.getDepName());
            if (flag == 1) {
                AutoApply newAutoApply = new AutoApply();
                newAutoApply.setAutoApplyId(autoApply.getAutoApplyId());
                newAutoApply.setModifyTime(new Date());
                newAutoApply.setModifierId(loginUser.getEmployeeId());
                newAutoApply.setStatus(new Short("4"));
                autoApplyMapper.updateByPrimaryKeySelective(newAutoApply);
            }
        }
    }

    /**
     * 修改任务状态，设置驳回到创建人
     */
    private int rejectTask(CarTransferVo carTransferVo, Map map, EmployeeVo loginUser) {
        //驳回到创建人
        map.put(ActivitiConstants.MANUAL_PERSON, new ArrayList<>(Arrays.asList(carTransferVo.getCreateUser())));
        updateAutoApplies(carTransferVo.getAutoApplyId(), loginUser, 1);
        carTransferVo.setState(2);
        return carTransferMapper.updateByPrimaryKeySelective(carTransferVo);
    }
}
